﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess;
using Models;
using System.Speech.Recognition;
using SpeechLib;
using System.Speech.Synthesis;
using System.IO;
using System.Text;
using System.Globalization;

namespace ClickRead.Controllers
{
  public class GlobalController : Controller
  {
    Repository repository;
    bool completed;
    public GlobalController()
    {
      string connection = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ClickReadConnectionString"].ConnectionString;
      this.repository = new Repository(connection);
    }

    public JsonResult GetBooks()
    {
      return Json(this.repository.GetBooks(), JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetPage(int bookId, int pageId)
    {
      return Json(this.repository.GetPage(bookId, pageId), JsonRequestBehavior.AllowGet);
    }

    public ActionResult GenerateAudioFiles(Stream audioStream)
    {
      var t = new System.Threading.Thread(() =>
      { 
        SystemHelper.GenerateAudios(Server.MapPath("/res/audio/"), this.repository);
      });
      t.Start();
      t.Join();
      return Content(string.Empty);
    }

    [HttpPost]
    public ActionResult SpeechRecognition()
    {
      byte[] audioData = null;
      if (Request.ContentLength > 0)
      {
        audioData = new byte[Request.ContentLength];
        using (BinaryReader br = new BinaryReader(Request.InputStream))
          br.Read(audioData, 0, audioData.Length);
      }
      else
      {
        return Content(string.Empty);
      }

      string txt = null;
      RecognitionResult result = null;
      var t = new System.Threading.Thread(() =>
      {
        using (MemoryStream stream = new MemoryStream(audioData))
        {
          result = SystemHelper.SpeechToText(stream);
          txt = "returned";
        };
      });
      t.Start();
      t.Join();
      while (string.IsNullOrEmpty(txt))
      {
      }

      if (result != null)
      {
        return Json(new { Alternates = result.Alternates.Select(a => a.Text).ToList() });
      }
      else
      {
        return Json(new { Alternates = new List<string>() });
      }
    }
  }
}
